package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.vo.AttrGroupRelationVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;


@Service("attrAttrgroupRelationService")
public class AttrAttrgroupRelationServiceImpl extends ServiceImpl<AttrAttrgroupRelationDao, AttrAttrgroupRelationEntity> implements AttrAttrgroupRelationService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrAttrgroupRelationEntity> page = this.page(
                new Query<AttrAttrgroupRelationEntity>().getPage(params),
                new QueryWrapper<AttrAttrgroupRelationEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveBatchRelations(List<AttrGroupRelationVo> vos) {
        //关系表已经存在attrid，但是attr_group_id为null的情况，直接update，  其他的进行save
        HashMap<Long, Long> map = new HashMap<>();
        List<Long> idList = vos.stream().map((item) -> {
            map.put(item.getAttrId(), item.getAttrGroupId());
            return item.getAttrId();
        }).collect(Collectors.toList());
        //所有在表中的数据  .eq("attr_group_id",null)
        List<AttrAttrgroupRelationEntity> relationEntities = this.baseMapper.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_id", idList));
        Set<Long> set = new HashSet<>();
        List<AttrAttrgroupRelationEntity> collect = relationEntities.stream().map((item) -> {
            //将vos中的goupid放进来
            item.setAttrGroupId(map.get(item.getAttrId()));
            set.add(item.getAttrId());
            return item;
        }).collect(Collectors.toList());
        //更新已经存在
        if (collect.size()!=0){
            this.updateBatchById(collect);
        }



        //保存不存在的
        List<AttrAttrgroupRelationEntity> entities = vos.stream().filter((item)->{
            //过滤已经存在的
            return !set.contains(item.getAttrId());
        }).map((item) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());
        if (entities!=null){
            this.saveBatch(entities);
        }
    }

}